(function ($) {
    $.fn.yqHtmlEdit = function (opts, param) {
        if (typeof opts == 'string') {
            return $.fn.yqHtmlEdit.methods[opts](this, param);
        }

        return this.each(function () {
            var $this = $(this);
            var opt;
            if ($this.data("yqtype") == "yqHtmlEdit") {
                var $uniqueID = $this.attr("ID");
                var opts_ = $.extend({}, options($this));
                destroy($this);
                $this = $("#" + $uniqueID);
                opt = $.extend(opts_, opts);
            }
            else {
                opt = $.extend({}, $.fn.yqHtmlEdit.defaults, opts);
                var $uniqueID = $this.attr("ID");
                if ($uniqueID === undefined || $uniqueID === null || $uniqueID == "") {
                    $uniqueID = $.getUniqueID();
                    $this.attr("ID", $uniqueID);
                }
            }

            opt.edit_files = [];     //选择后，未上传文件列表
            opt.html_files = [];     //原网页文件信息 + 已上传文件

            if (opt.width === undefined && $this.width() > 0) {
                opt.width = $this.width();
            }
            else if (typeof opt.width != "undefined") {
                $this.width(opt.width);
            }

            if (opt.height === undefined && $this.height() > 0) {
                opt.height = $this.height();
            }
            else if (typeof opt.height != "undefined") {
                $this.height(opt.height);
            }

            if ($this[0].tagName.toLowerCase() != "textarea") {
                var $uniqueID = $this.attr("id");
                $this.removeAttr("id");
                $this.after('<textarea id="' + $uniqueID + '" style="width: ' + opt.width + 'px;height:' + opt.height + 'px;"></textarea>')
                $this.remove();
                $this = $("#" + $uniqueID)
            }

            //组件加载结束
            opt.onload = true;
            //组件进程执行中
            opt.running = false;

            //变量信息
            $this.data("htmledit_opt", opt);
            $this.data("yqtype", "yqHtmlEdit");
            var $object = $this;
            LoadJsCss(function () {
                init_edit($object);
            });
        });
    };

    // plugins: 'link image imagetools media hr textcolor link lists advlist charmap code table  fullscreen preview codesample quickbars searchreplace wordcount', //插件
    // toolbar: 'undo redo | styles  forecolor | bold italic underline removeformat| link unlink image media table charmap hr | alignleft aligncenter alignright alignjustify | bullist numlist  | outdent indent | searchreplace wordcount code fullscreen preview',
    $.fn.yqHtmlEdit.defaults = {
        
        storageType: 3,//1-数据库存储，2-外部存储 其他-路径
        storageName: null,
        accept: "image/*",
        chunk: false,       //分片上传
        directup: false,    //直接上传（选择文件后立即上传）
        data: { files: [], html: "" },
        isEdit: true,   //可编辑


        lang: 'zh-Hans', //语言
        plugins: 'link image media link lists advlist charmap code table  fullscreen preview codesample searchreplace wordcount', //插件
        toolbar: 'undo redo | styles  forecolor | bold italic underline removeformat| link unlink image media table charmap hr | alignleft aligncenter alignright alignjustify | bullist numlist  | outdent indent | searchreplace wordcount code fullscreen preview',
        menubar: false, //隐藏菜单栏
        content_css: [],
    };

    $.fn.yqHtmlEdit.methods = {
        options: function (jq) {
            return options($(jq[0]));
        },
        destroy: function (jq) {
            destroy($(jq[0]));
        },
        resize: function (jq, params) {
            resize($(jq[0]), params);
        },
        clear: function (jq, data) {
            setValue($(jq[0]), null);
        },
        setData: function (jq, data) {
            setData($(jq[0]), data);
        },
        getData: function (jq) {
            return getData($(jq[0]));
        },
        disable: function (jq) {
            isEdit($(jq[0]), false);
        },
        enable: function (jq) {
            isEdit($(jq[0]), true);
        },
    };

    function LoadJsCss(callback) {
        var file = [];
        file.push({ url: "/scripts/crypto/sha256.min.js", type: "js" });
        file.push({ url: "/scripts/tinymce/tinymce.min.js", type: "js" });
        $.yqLoadJsCss(file, function () {
            callback();
        })
    }

    function options($object) {
        return $object.data("htmledit_opt");
    }

    function destroy($object) {
        var $uniqueID = $object.attr("id");
        var editor = tinymce.get($uniqueID);
        editor.destroy();
        $object.removeData("htmledit_opt");
        $object.removeData("yqtype");
    }

    function resize($object, params) {
        var opt = options($object);
        var $uniqueID = $object.attr("id");
        if (typeof params == "object") {
            if (typeof params.width != "undefined") {
                opt.width = params.width;
            }
            if (typeof params.height != "undefined") {
                opt.height = params.height;
            }
        }
        var editor = tinymce.get($uniqueID);
        editor.editorContainer.style.width = opt.width + 'px';
        editor.editorContainer.style.height = opt.height + 'px';
    }

    function init_edit($object) {
        var opt = options($object);
        var $uniqueID = $object.attr("id");

        tinymce.init({
            selector: '#' + $uniqueID,
            promotion: false,
            branding: false,
            resize: false,
            language: opt.lang,
            plugins: opt.plugins,
            toolbar: opt.toolbar,
            menubar: opt.menubar, //隐藏菜单栏
            content_css: opt.content_css,
            image_title: true, // 是否开启图片标题设置的选择，这里设置否
            automatic_uploads: true, //开启点击图片上传时，自动进行远程上传操作
            images_upload_url: null,
            file_picker_callback: function (callback, value, meta) {
                if (!(opt.storageType == 1 || opt.storageType == 2)) {
                    return;
                }

                //文件分类
                var filetype = '.pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4';
                //后端接收上传文件的地址
                // var upurl = '_rteditor.html';
                //为不同插件指定文件类型及后端地址
                switch (meta.filetype) {
                    case 'image':
                        filetype = '.jpg, .jpeg, .png, .gif';
                        // upurl = '_rteditor.html';
                        break;
                    case 'media':
                        filetype = '.mp3, .mp4';
                        // upurl = '_rteditor.html';
                        break;
                    case 'file':
                    default:
                }

                var input = document.createElement('input');
                input.setAttribute('type', 'file');
                input.setAttribute('accept', filetype);
                input.click();
                input.onchange = function () {
                    var file = this.files[0];
                    console.log("file", file);
                    fileUpload($object, file, function (tf, url, info) {
                        if (tf) {
                            callback(url, info);
                        }
                    });
                };
            },
            // images_upload_handler: function (blobInfo, progress, succFun, failFun) {
            //     var file = blobInfo.blob();//转化为易于理解的file对象
            //     console.log("images_upload_handler", file);
            //     fileUpload($object, file, function (tf, url, info) {
            //         console.log(tf,url);
            //         if (tf) {
            //             succFun(url);
            //         }else{
            //             failFun(url);
            //         }
            //     });
            // }
        }).then((editors) => {
            opt.onload = false;
            isEdit($object, opt.isEdit);
            resize($object);
        });

        if (opt.data.html != "") {
            setData($object, opt.data);
        }
    }

    function fileUpload($object, file, callback) {
        var opt = options($object);

        if (!opt.directup) {
            var reader = new FileReader();
            reader.onload = function () {
                var id = 'blobid' + (new Date()).getTime();
                var blobCache = tinymce.activeEditor.editorUpload.blobCache;
                var base64 = reader.result.split(',')[1];
                var blobInfo = blobCache.create(id, file, base64);
                blobCache.add(blobInfo);
                opt.edit_files.push({ blobUri: blobInfo.blobUri(), file: file })
                callback(true, blobInfo.blobUri(), { title: file.name });
            };
            reader.readAsDataURL(file);
            return;
        }

        if (opt.storageType == 2 && opt.chunk) {
            $.yqFileChunkUpload(file, {
                ajaxUrl: '/_file.html',
                // sto_type: opt.storageType,     //1-数据库存储，2-外部存储
                sto_name: opt.storageName,     //外部存储库名
                // 上传完成
                success: function (res) {
                    if (res.error == 0) {
                        opt.html_files.push(res.file);
                        var f_url;
                        if (res.file.sto_type == 1) {
                            f_url = "!" + res.file.sto_name + "_" + res.file.sid;
                        } else if (res.file.sto_type == 2) {
                            f_url = "^" + res.file.sto_name + "_" + res.file.sid;
                        }
                        callback(true, f_url, { title: res.file.name });
                        $.yqMessager("success", "上传成功。");
                    } else {
                        callback(false, res.info + "[" + res.error + "]", {});
                        $.yqMessager("error", res.info + "[" + res.error + "]");

                    }
                },
            })
        } else {
            $.yqFileUpload(file, {
                ajaxUrl: '/_file.html',
                sto_type: opt.storageType,     //1-数据库存储，2-外部存储
                sto_name: opt.storageName,     //外部存储库名
                // 上传完成
                success: function (res) {
                    if (res.error == 0) {
                        opt.html_files.push(res.file);
                        var f_url;
                        if (res.file.sto_type == 1) {
                            f_url = "!" + res.file.sto_name + "_" + res.file.sid;
                        } else if (res.file.sto_type == 2) {
                            f_url = "@" + res.file.sto_name + "_" + res.file.sid;
                        }
                        callback(true, f_url, { title: res.file.name });
                        $.yqMessager("success", "上传成功。");
                    } else {
                        callback(false, res.info + "[" + res.error + "]", {});
                        $.yqMessager("error", res.info + "[" + res.error + "]");
                    }
                },
            })
        }
    };



    function setData($object, data) {
        var opt = options($object);
        if (!opt.onload) {
            setDataRun($object, data);
        }
        else {
            setTimeout(function () {
                setData($object, data);
            }, 500);
        }
    }

    function setDataRun($object, data) {
        var opt = options($object);
        var $uniqueID = $object.attr("id");

        if (typeof data == "string") {
            data = JSON.parse(data);
        }
        else if (typeof data != "object") {
            data = null;
        }
        if (data === null) {
            data = { files: [], html: "" };
        }
        opt.data = data;
        //选择后，未上传文件列表
        if (data.edit_files === undefined) {
            opt.edit_files = [];
        } else {
            opt.edit_files = data.edit_files;
        }
        opt.html_files = data.files;     //原网页文件信息 + 已上传文件

        var editor = tinymce.get($uniqueID);
        //console.log(editor);
        editor.setContent(data.html);
    }

    function getData($object) {
        var opt = options($object);
        var $uniqueID = $object.attr("id");
        var data = { edit_files: [], files: [], html: "" };
        var editor = tinymce.get($uniqueID);
        var $html = $("<div>" + editor.getContent({ source_view: true }) + "</div>");
        var $imgs = $html.find("img");
        for (let i = 0; i < $imgs.length; i++) {
            var $img = $($imgs[i]);
            var src = $img.attr("src");
            if (src.substring(0, 5) == "blob:") {
                for (let j = 0; j < opt.edit_files.length; j++) {
                    if (src == opt.edit_files[j].blobUri) {
                        data.edit_files.push(opt.edit_files[j]);
                    }
                }
            } else {
                var filename = src;
                if (filename.lastIndexOf("/") > 0) {
                    filename = filename.substring(filename.lastIndexOf("/") + 1, filename.length);
                }
                var sto_type = 1;
                var sto_name = "";
                var sid = "";
                if (filename.substring(0, 1) == "!") {
                    sto_type = 1;
                } else if (filename.substring(0, 1) == "@") {
                    sto_type = 2;
                }
                var f_names = filename.substring(1, filename.length).split("_");
                sto_name = f_names[0];
                sid = f_names[1];
                var has_dip = false;
                for (let j = 0; j < opt.html_files.length; j++) {
                    if (sto_type == opt.html_files[j].sto_type &&
                        sto_name == opt.html_files[j].sto_name &&
                        sid == opt.html_files[j].sid) {
                        var has_f = false;
                        for (let l = 0; l < data.files.length; l++) {
                            if (sto_type == data.files[l].sto_type &&
                                sto_name == data.files[l].sto_name &&
                                sid == data.files[l].sid) {
                                has_f = true;
                            }
                        }
                        if (!has_f) {
                            data.files.push(opt.html_files[j]);
                        }
                        has_dip = true;
                        break;
                    }
                }

                // type Field_File struct {
                //     Sid         string `json:"sid" sql:"sid"`
                //     StorageType int    `json:"sto_type" sql:"sto_type"`
                //     StorageName string `json:"sto_name" sql:"sto_name"`
                //     Name        string `json:"name" sql:"name"`
                //     Size        int    `json:"size" sql:"size"`
                //     Type        string `json:"type" sql:"type"`
                //     //Finger      string `json:"finger" sql:"finger"`
                // }

                if (!has_dip) {
                    data.files.push({
                        sid: sid,
                        sto_type: sto_type,
                        sto_name: sto_name
                    });
                }
            }
        }

        data.html = $html.html();

        return data;
    }

    function isEdit($object, tf) {
        var opt = options($object);
        var $uniqueID = $object.attr("id");
        var editor = tinymce.get($uniqueID);
        opt.isEdit = tf;
        if (tf) {
            editor.mode.set('design');
        } else {
            editor.mode.set('readonly');
        }
    }
})(jQuery);